package com.zf.shuashua;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.MainThread;
import androidx.annotation.Nullable;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAppDownloadListener;
import com.bytedance.sdk.openadsdk.TTSplashAd;
import com.dydroid.ads.c.ADError;
import com.dydroid.ads.c.splash.SplashADListener;
import com.dydroid.ads.c.splash.SplashAdLoader;
import com.huawei.openalliance.ad.inter.HiAd;
import com.lxj.xpopup.XPopup;
import com.meis.base.mei.utils.Eyes;
import com.meis.base.mei.utils.ParseJsonUtils;
import com.zf.shuashua.advert.MistakeConfigManager;
import com.snail.antifake.jni.EmulatorDetectUtil;
import com.umeng.message.UmengNotifyClickActivity;
import com.umeng.message.entity.UMessage;
import com.vise.utils.view.DialogUtil;
import com.zf.shuashua.advert.AdReportManager;
import com.zf.shuashua.advert.AdvertConfigManager;
import com.zf.shuashua.advert.CommitUtils;
import com.zf.shuashua.advert.TTAdManagerHolder;
import com.zf.shuashua.api.AbsCallback;
import com.zf.shuashua.api.HttpData;
import com.zf.shuashua.api.Store;
import com.zf.shuashua.bean.AdvertReport;
import com.zf.shuashua.bean.BaseData;
import com.zf.shuashua.bean.ExtraBean;
import com.zf.shuashua.bean.advert.AdvertConfigBean;
import com.zf.shuashua.bean.advert.AdvertConfigList;
import com.zf.shuashua.bean.advert.DrawConfigBean;
import com.zf.shuashua.bean.advert.HorizontalConfigBean;
import com.zf.shuashua.bean.advert.OpenConfigBean;
import com.zf.shuashua.manager.ActionThirdReportManager;
import com.zf.shuashua.manager.ReportChannelManager;
import com.zf.shuashua.manager.ShunInitialManager;
import com.zf.shuashua.ui.home.PrivacyPopup;
import com.zf.shuashua.ui.popup.OnPopupListener;
import com.zf.shuashua.utils.RunLinuxCommand;
import com.zf.shuashua.utils.UIUtils;
import com.zf.shuashua.utils.Util;

import org.android.agoo.common.AgooConstants;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class SplashActivity extends UmengNotifyClickActivity{
    private FrameLayout mSplashContainer;
    private TextView mTvSkip;
    //开屏广告加载超时时间,建议大于3000,这里为了冷启动第一次加载到广告并且展示,示例设置了3000ms
    private static final int AD_TIME_OUT = 3500;
    private String mCodeId = "887302592";
    private String mWxId = "D1050084";
    private boolean mIsExpress = false; //是否请求模板广告
    private int count = 5;
    private MyCountDownTimer myCountDownTimer;

    public boolean canJump = false;
    private SplashAdLoader splashAdLoader;
    private int loadCount = 0;
    private boolean isDisSkip;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Eyes.translucentStatusBar(this, true);
        setContentView(R.layout.activity_splash);
//        if (!isTaskRoot()) {
//            finish();
//            return;
//        }
        //检查隐私政策
        // 获取是否已经同意过隐私政策
        if (!Store.getInstance().getPrivacy()) {
            showPrivacyPolicyDialog();
        } else {
            agreePrivacyNext(false);
        }
    }

    /**
     * 展示隐私政策弹框
     */
    private void showPrivacyPolicyDialog() {
        //隐私政策
        XPopup.setAnimationDuration(10);
        PrivacyPopup privacyPopup = new PrivacyPopup(this);
        privacyPopup.setPopupListener(new OnPopupListener() {
            @Override
            public void onNext() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //同意隐私政策
                        agreePrivacyNext(true);
                    }
                }, 100);
            }

            @Override
            public void onClose() {
                finish();
            }
        });
        new XPopup.Builder(this)
                .dismissOnTouchOutside(false)
                .dismissOnBackPressed(false)
                .asCustom(privacyPopup)
                .show();
    }

    /**
     * 同意隐私协议后，继续正常的业务逻辑
     */
    private void agreePrivacyNext(boolean withInit) {
        if (!checkValidPhone()) {
            return;
        }
        if (Store.getInstance().getNewUserTpAd() <= 1) {
            Store.getInstance().setNewUserTpAd(Store.getInstance().getNewUserTpAd() + 1);
        }

        if(withInit){
            ShunInitialManager.getInstance().initCommon(this);
        }
        // 设置已同意用户协议标识，前面已经判断是否同意过用户协议，在这里再次调用一下；手机克隆场景，有可能会丢失保存的同意标识。
        HiAd.getInstance(this).enableUserInfo(true);

        initView();
        if (Build.VERSION.SDK_INT >= 23) {
            checkAndRequestPermission();
        } else {
            doFetch();
        }
    }

    @Override
    public void onMessage(Intent intent) {
        super.onMessage(intent);
        if (intent != null) {
            final String body = intent.getStringExtra(AgooConstants.MESSAGE_BODY);
            if (body != null) {
                UMessage result = ParseJsonUtils.parseData(body, UMessage.class);
                ExtraBean extraBean;
                try {
                    JSONObject object = new JSONObject(result.extra);
                    int type = object.getInt("type");
                    if (type == 1) {
                        extraBean = new ExtraBean();
                        extraBean.setType(type);
                        extraBean.setOpen_id(object.getInt("open_id"));
                        EventBus.getDefault().postSticky(extraBean);
                    } else if (type == 2) {
                        extraBean = new ExtraBean();
                        extraBean.setType(type);
                        extraBean.setUser_id(object.getInt("user_id"));
                        EventBus.getDefault().postSticky(extraBean);
                    } else if (type == 3) {
                        extraBean = new ExtraBean();
                        extraBean.setType(type);
                        extraBean.setVideo_id(object.getInt("video_id"));
                        EventBus.getDefault().postSticky(extraBean);
                    } else if (type == 4) {
                        extraBean = new ExtraBean();
                        extraBean.setType(type);
                        EventBus.getDefault().postSticky(extraBean);
                    } else if (type == 5) {
                        extraBean = new ExtraBean();
                        extraBean.setType(type);
                        EventBus.getDefault().postSticky(extraBean);
                    } else if (type == 6) {
                        extraBean = new ExtraBean();
                        extraBean.setType(type);
                        EventBus.getDefault().postSticky(extraBean);
                    } else if (type == 7) {
                        extraBean = new ExtraBean();
                        extraBean.setType(type);
                        EventBus.getDefault().postSticky(extraBean);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void initView() {
        mSplashContainer = findViewById(R.id.splash_container);
        mSplashContainer.setVisibility(View.VISIBLE);
        mTvSkip = findViewById(R.id.tv_skip);
        //同步上次的误触配置
        MistakeConfigManager.getInstance().syncConfig();
        isDisSkip = MistakeConfigManager.getInstance().isDisSkip();
    }

    private void doFetch() {
        getConfigInfo();
        reportChannel();
        fetchAdvert();
    }

    private void fetchAdvert() {
        syncAdvertSource();
        List<AdvertConfigBean> openList = Store.getInstance().getOpenConfig();
        if (openList != null && openList.size() > 0) {
            OpenConfigBean openConfigBean = new OpenConfigBean();
            openConfigBean.setOpen(openList);
            openConfigBean.setIndexOpen(Store.getInstance().getOpenIndex());
            ShuaApplication.openConfig = openConfigBean;
            AdvertConfigBean config = openConfigBean.getOpenConfig();
            String codeId = config.getOrigin_id();
            if(CommitUtils.isVivoClose() || CommitUtils.isHuaweiClose()){
                loadAdvertConfig();
            }else {
                if (config.isSelf()) {
//                    loadSelfAdvert(codeId);
                    loadSplashAd("");
                } else if (config.isTencent()) {
//                    loadTencentSplash(codeId);
                    loadSplashAd("");
                } else if (config.isWangXiang()) {
                    loadAds();
                } else {
                    loadSplashAd(codeId);
                }
            }
        } else {
            if(CommitUtils.isVivoClose() || CommitUtils.isHuaweiClose()){
                loadAdvertConfig();
            }else {
                loadSplashAd("");
            }
        }
    }

    /**
     * 华为、vivo未知审核状态时，需要先获取审核开关
     */
    private void loadAdvertConfig(){
        HttpData.getInstance().getNewAdvertConfig(new AbsCallback<BaseData<AdvertConfigList>>() {
            @Override
            public void onRealSuccess(BaseData<AdvertConfigList> data) {
                AdvertConfigManager.getInstance().saveAdvertConfig(data);
                if(CommitUtils.isVivoClose() || CommitUtils.isHuaweiClose()){
                    goToMainActivity();
                }else{
                    loadSplashAd("");
                }
            }

            @Override
            public void onFail(int errCode, String errMsg) {
                goToMainActivity();
            }
        });
    }

    private void syncAdvertSource() {
        Store store = Store.getInstance();
        ShuaApplication.city = store.getLastLocation();
        ShuaApplication.isVivoOpen = store.getVivoOpen();
        ShuaApplication.isHuaweiOpen = store.getHuaweiOpen();
        ShuaApplication.isXiaomiOpen = store.getXiaomiOpen();
        List<AdvertConfigBean> drawList = store.getDrawConfig();
        if (drawList != null && drawList.size() > 0) {
            DrawConfigBean drawConfigBean = new DrawConfigBean();
            drawConfigBean.setDrawing(drawList);
            if (ShuaApplication.drawConfig == null) {
                drawConfigBean.setIndexDraw(Store.getInstance().getDrawIndex());
                ShuaApplication.drawConfig = drawConfigBean;
            }
        }
        List<AdvertConfigBean> horizontalList = store.getHorizontalConfig();
        if (horizontalList != null && horizontalList.size() > 0) {
            HorizontalConfigBean horizontalConfig = new HorizontalConfigBean();
            horizontalConfig.setHorizontal(horizontalList);
            if (ShuaApplication.horizontalConfig == null) {
                ShuaApplication.horizontalConfig = horizontalConfig;
            }
        }
    }

    private boolean checkValidPhone() {
        if (EmulatorDetectUtil.isEmulator()) {
            showAdoptDialog();
            return false;
        }
        if (RunLinuxCommand.isDeviceRooted()) {
            showRootDialog();
            return false;
        }
        return true;
    }

    private void getConfigInfo() {
        AdvertConfigManager.getInstance().fetchConfigInfo();
    }

    /**
     * 上报渠道的下载数
     */
    private void reportChannel() {
        ReportChannelManager.getInstance().reportChannelData(2);
    }

    private void showAdoptDialog() {
        DialogUtil.dialogBuilder(this, "提醒", "你使用的是模拟器，请关闭").
                setCancelable(false).
                setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        SplashActivity.this.finish();
                    }
                }).show();
    }

    private void showRootDialog() {
        DialogUtil.dialogBuilder(this, "提醒", "你的手机已经被Root，不能使用本产品，请关闭Root之后再试").
                setCancelable(false).
                setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        SplashActivity.this.finish();
                    }
                }).show();
    }

    private String uuiThirdAdvert;
    private String planId;

    private void reportRequestStart(int advert_way, String code_bit) {
        ActionThirdReportManager.getInstance().reportRequestStart(advert_way, 1, code_bit, 1);
    }

    private void reportRequestSucc(int advert_way, String code_bit, int return_num) {
        ActionThirdReportManager.getInstance().reportRequestSucc(advert_way, 1, code_bit, return_num);
    }

    private void reportRequestFail(int advert_way, String code_bit, String error_code, String error_msg) {
        ActionThirdReportManager.getInstance().reportRequestFail(advert_way, 1, code_bit, 1, error_code, error_msg);
    }

    private void tryLoadTencentSplash() {
        //            if (loadCount >= 2) {
        //                goToMainActivity();
        //            } else {
        //                loadTencentSplash("");
        //            }
        runOnUiThread(this::goToMainActivity);
    }

    private void loadAds(){
        loadCount++;
        uuiThirdAdvert = Util.getUUID32();
        mSplashContainer.setVisibility(View.VISIBLE);
        mTvSkip.setVisibility(View.GONE);

        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,FrameLayout.LayoutParams.WRAP_CONTENT);
        params.topMargin = 70;
        params.rightMargin = 60;

        splashAdLoader = new SplashAdLoader(this, mWxId, mSplashContainer, new SplashADListener() {

            @Override
            public void onADError(ADError adError) {
                runOnUiThread(() -> {
                    if (loadCount >= 2) {
                        goToMainActivity();
                    } else {
                        loadSplashAd("");
                        if (adError != null) {
                            reportRequestFail(9, mWxId, adError.getErrorCode() + "", adError.getErrorMessage() + "");
                        }
                    }
                });
            }

            @Override
            public void onADClicked() {
                AdReportManager.getInstance().reportAdvertAction(uuiThirdAdvert, planId, AdvertReport.EventType.ImageClick, 1 + "", "9");
            }

            @Override
            public void onADShow() {
                AdReportManager.getInstance().reportAdvertAction(uuiThirdAdvert, planId, AdvertReport.EventType.ImageShow, 1 + "", "9");
                reportRequestSucc(9, mWxId, 1);
            }

            @Override
            public void onADExposure() {
            }

            @Override
            public void onADDismissed() {
                next();
            }
        });
        planId = System.identityHashCode(splashAdLoader) + "";


        splashAdLoader.load();
        reportRequestStart(9, mWxId);

    }

    /**
     * 穿山甲
     */
    private void loadSplashAd(String codeId) {
        mCodeId = TextUtils.isEmpty(codeId) ? AdvertUtils.getSplashId() : codeId;
        loadCount++;
        uuiThirdAdvert = Util.getUUID32();
        TTAdNative mTTAdNative = TTAdManagerHolder.get().createAdNative(this);
        //step3:创建开屏广告请求参数AdSlot,具体参数含义参考文档
        AdSlot adSlot = null;
        //setImageAcceptedSize是px setExpressViewAcceptedSize是dp
        if (mIsExpress) {
            //个性化模板广告需要传入期望广告view的宽、高，单位dp，请传入实际需要的大小，
            //比如：广告下方拼接logo、适配刘海屏等，需要考虑实际广告大小
            float expressViewWidth = UIUtils.getScreenWidthDp(this);
            float expressViewHeight = UIUtils.getHeight(this);
            adSlot = new AdSlot.Builder()
                    .setCodeId(mCodeId)
                    .setSupportDeepLink(true)
//                    .setImageAcceptedSize(1080, 1920)
                    //模板广告需要设置期望个性化模板广告的大小,单位dp,代码位是否属于个性化模板广告，请在穿山甲平台查看
                    .setExpressViewAcceptedSize(expressViewWidth, expressViewHeight)
                    .build();
        } else {
            int expressViewWidth = UIUtils.getScreenWidthPx(this);
            int expressViewHeight = UIUtils.getScreenHeightPx(this);
            adSlot = new AdSlot.Builder()
                    .setCodeId(mCodeId)
                    .setSupportDeepLink(true)
                    .setImageAcceptedSize(expressViewWidth, expressViewHeight)
                    .build();
        }


        //step4:请求广告，调用开屏广告异步请求接口，对请求回调的广告作渲染处理
        mTTAdNative.loadSplashAd(adSlot, new TTAdNative.SplashAdListener() {
            @Override
            @MainThread
            public void onError(int code, String message) {
                tryLoadTencentSplash();
                reportRequestFail(1, mCodeId, code + "", message);
            }

            @Override
            @MainThread
            public void onTimeout() {
                tryLoadTencentSplash();
                reportRequestFail(1, mCodeId, "408", "time out");
            }

            @Override
            @MainThread
            public void onSplashAdLoad(TTSplashAd ad) {
                if (ad == null) {
                    tryLoadTencentSplash();
                    reportRequestSucc(1, mCodeId, 0);
                    return;
                }
                //获取SplashView
                View view = ad.getSplashView();
                if (mSplashContainer != null && !SplashActivity.this.isFinishing()) {
                    //设置不开启开屏广告倒计时功能以及不显示跳过按钮,如果这么设置，您需要自定义倒计时逻辑
                    ad.setNotAllowSdkCountdown();
                    mSplashContainer.removeAllViews();
                    //把SplashView 添加到ViewGroup中,注意开屏广告view：width >=70%屏幕宽；height >=50%屏幕高
                    mSplashContainer.addView(view);
//                    startCountTime();
                    reportRequestSucc(1, mCodeId, 1);
                } else {
                    tryLoadTencentSplash();
                    reportRequestSucc(1, mCodeId, 0);
                    return;
                }

                String planId = System.identityHashCode(ad) + "";
                //设置SplashView的交互监听器
                ad.setSplashInteractionListener(new TTSplashAd.AdInteractionListener() {
                    @Override
                    public void onAdClicked(View view, int type) {
                        AdReportManager.getInstance().reportAdvertAction(uuiThirdAdvert, planId, AdvertReport.EventType.ImageClick, 1 + "");
                    }

                    @Override
                    public void onAdShow(View view, int type) {
                        startCountTime();
                        AdReportManager.getInstance().reportAdvertAction(uuiThirdAdvert, planId, AdvertReport.EventType.ImageShow, 1 + "");
                    }

                    @Override
                    public void onAdSkip() {
                        goToMainActivity();
                    }

                    @Override
                    public void onAdTimeOver() {
                        goToMainActivity();
                    }
                });
                if (ad.getInteractionType() == TTAdConstant.INTERACTION_TYPE_DOWNLOAD) {
                    ad.setDownloadListener(new TTAppDownloadListener() {
                        boolean hasShow = false;

                        @Override
                        public void onIdle() {
                        }

                        @Override
                        public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {
                            if (!hasShow) {
                                hasShow = true;
                            }
                        }

                        @Override
                        public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {

                        }

                        @Override
                        public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) {

                        }

                        @Override
                        public void onDownloadFinished(long totalBytes, String fileName, String appName) {

                        }

                        @Override
                        public void onInstalled(String fileName, String appName) {

                        }
                    });
                }
            }
        }, AD_TIME_OUT);
        reportRequestStart(1, mCodeId);
    }

    private void goToMainActivity() {
        Intent intent = new Intent(SplashActivity.this, MainActivity.class);
        SplashActivity.this.startActivity(intent);
//        if(mSplashContainer != null){
//            mSplashContainer.removeAllViews();
//        }
        this.finish();
    }

    private void startCountTime() {
        mTvSkip.setText("跳过 " + count);
        mTvSkip.setVisibility(View.VISIBLE);
        if (!isDisSkip) {
            mTvSkip.setOnClickListener(v -> {
                goToMainActivity();
            });
        }
        myCountDownTimer = new MyCountDownTimer(count * 1000 + 1300, 1000);
        myCountDownTimer.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (myCountDownTimer != null) {
            myCountDownTimer.cancel();
            myCountDownTimer = null;
        }
        try{
            if(splashAdLoader != null){
                splashAdLoader.release();
                splashAdLoader = null;
            }
        }catch (Exception ignored){

        }
    }

    private class MyCountDownTimer extends CountDownTimer {

        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        //计时过程
        @Override
        public void onTick(long l) {
            int count = (int) l / 1000 - 1;
            if (count < 0) {
                count = 0;
            }
            if (mTvSkip != null) {
                mTvSkip.setText("跳过 " + count);
            }
        }

        //计时完毕的方法
        @Override
        public void onFinish() {
            next();
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    private void checkAndRequestPermission() {
        List<String> lackedPermission = new ArrayList<String>();
        if (!(checkSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED)) {
            lackedPermission.add(Manifest.permission.READ_PHONE_STATE);
        }

        if (!(checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)) {
            lackedPermission.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        }

        if (!(checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)) {
            lackedPermission.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }

        if (!(checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)) {
            lackedPermission.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        }
        if (!(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)) {
            lackedPermission.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }

        // 如果需要的权限都已经有了，那么直接调用SDK
        if (lackedPermission.size() == 0) {
            doFetch();
        } else {
            // 否则，建议请求所缺少的权限，在onRequestPermissionsResult中再看是否获得权限
            String[] requestPermissions = new String[lackedPermission.size()];
            lackedPermission.toArray(requestPermissions);
            requestPermissions(requestPermissions, 1024);
        }
    }

    private boolean hasAllPermissionsGranted(int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult == PackageManager.PERMISSION_DENIED) {
                return false;
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        if (requestCode == 1024 && hasAllPermissionsGranted(grantResults)) {
//            doFetch();
//        } else {
//            Toast.makeText(this, "应用缺少必要的权限！请点击\"权限\"，打开所需要的权限。", Toast.LENGTH_LONG).show();
//            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
//            intent.setData(Uri.parse("package:" + getPackageName()));
//            startActivity(intent);
//            finish();
//        }
        doFetch();
    }

    /**
     * 开屏页一定要禁止用户对返回按钮的控制，否则将可能导致用户手动退出了App而广告无法正常曝光和计费
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 设置一个变量来控制当前开屏页面是否可以跳转，当开屏广告为普链类广告时，点击会打开一个广告落地页，此时开发者还不能打开自己的App主页。当从广告落地页返回以后，
     * 才可以跳转到开发者自己的App主页；当开屏广告是App类广告时只会下载App。
     */
    private void next() {
        if (canJump) {
            goToMainActivity();
        } else {
            canJump = true;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        canJump = false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (canJump) {
            next();
        }
        canJump = true;
    }
}
